package org.flowers.unbeaten.util;

import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

/**
 * @description 获取http上下文工具类
 * @author RyanWang
 * @date 2021-07-16 10:00:50
 * @version 1.0
 */
public class HttpContextUtils {

    /**
     * 获取HttpServlet请求
     * @return
     */
    public static HttpServletRequest getHttpServletRequest() {
        return ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
    }

    /**
     * 判断是否是Ajax请求
     * @param request
     * @return
     */
    public static boolean isAjaxRequest(HttpServletRequest request) {
        String accept = request.getHeader("accept");
        String xRequestedWith = request.getHeader("X-Requested-With");
        // 如果是异步请求或是手机端，则直接返回信息
        return ((accept != null && accept.contains("application/json") || (xRequestedWith != null && xRequestedWith.contains("XMLHttpRequest"))));
    }

}
